# -*- coding: utf-8 -*-
# @Time : 2022/7/8 10:22
# @FileName: AutoWechat.py
# @Mail: lizhigen1996@aliyun.com

__author__ = 'Zhigen.li'

import pyautogui
import time
import pyperclip
import json
from threading import Thread, Condition, Lock
from PyQt5.QtGui import QImage
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tbp.v20190627 import tbp_client, models
from res.resource_rc import *
from Config.Config import config
from Tools.Util import *
from lxml import etree
from requests import get, post
from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.base import STATE_RUNNING

PathPrefix = 'C:\\Config\\'
con = Condition(Lock())


class AutoWechat(object):
    def __init__(self):
        super(AutoWechat, self).__init__()
        self.condition = Condition
        img = QImage(':/Img/pos1.png')
        self.pos1 = PathPrefix + 'pos1.png'
        img.save(self.pos1)

        img = QImage(':/Img/send.png')
        self.sendimg = PathPrefix + 'send.png'
        img.save(self.sendimg)

        img = QImage(':/Img/block2.png')
        self.standby = PathPrefix + 'block2.png'
        img.save(self.standby)

        img = QImage(':/Img/xinxi.png')
        self.xinxi = PathPrefix + 'xinxi.png'
        img.save(self.xinxi)

        img = QImage(':/Img/red.png')
        self.red = PathPrefix + 'red.png'
        img.save(self.red)

        img = QImage(':/Img/pos3.png')
        self.pos3 = PathPrefix + 'pos3.png'
        img.save(self.pos3)

        img = QImage(':/Img/like.png')
        self.like = PathPrefix + 'like.png'
        img.save(self.like)

        img = QImage(':/Img/emoji.png')
        self.emoji = PathPrefix + 'emoji.png'
        img.save(self.emoji)

        img = QImage(':/Img/zhizhan.png')
        self.zhizhan = PathPrefix + 'zhizhan.png'
        img.save(self.zhizhan)

        self.isExit = False
        self.t = None
        self.sched = BlockingScheduler()
        self.s = Thread(target=self.schedTh)
        self.s.setDaemon(True)
        self.s.start()

    def schedTh(self):
        self.sched.add_job(self.tianqi, trigger='cron', hour='8,14', minute='0', name='tianqi')
        self.sched.add_job(self.dapan, trigger='cron', hour='11,14', minute='10', name='dapan1')
        self.sched.add_job(self.dapan, trigger='cron', hour='14', minute='45', name='dapan2')
        self.sched.start()

    def wechat_init(self):
        location3 = pyautogui.locateCenterOnScreen(self.sendimg, confidence=0.9)
        if location3 == None:
            pyautogui.hotkey('ctrl', 'alt', 'w')  # Ctrl + alt + w 打开微信
            time.sleep(0.5)
        loc = pyautogui.locateCenterOnScreen(self.xinxi, confidence=0.9)
        if loc:
            pyautogui.click(loc)
            time.sleep(0.5)

        while True:
            location1 = pyautogui.locateCenterOnScreen(self.pos1, confidence=0.9)
            # location2 = pyautogui.locateCenterOnScreen(pos2, confidence=0.9)
            location3 = pyautogui.locateCenterOnScreen(self.sendimg, confidence=0.9)
            location4 = pyautogui.locateCenterOnScreen(self.standby, confidence=0.9)
            if location1 and location3 and location4:
                break
            else:
                print("未打开微信,1秒后重试")
                time.sleep(1)
        print(location1)
        return location1, location3, location4

    # %% 找有没有新消息
    def mainWork(self):
        while True:
            location = pyautogui.locateCenterOnScreen(self.red, confidence=0.9)
            if location:
                break
            else:
                print("没有新消息,1秒后重试")
                time.sleep(1)
        return location

    def find_txt(self):
        locations = pyautogui.locateAllOnScreen(self.pos3)  # , confidence=0.9
        if not locations:
            print("没有消息,1秒后重试")
            return ''

        time.sleep(0.2)
        txt = list(locations)
        if txt != []:
            pos = sorted(txt, key=lambda x: x[1], reverse=True)[0]
            print(pos)
            pyautogui.doubleClick([pos[0] + 25, pos[1], pos[2], pos[3]])
            time.sleep(0.5)
            pyautogui.hotkey('ctrl', 'c')
            time.sleep(0.2)
            txt = pyperclip.paste()
            # print(str(txt))
        return str(txt)

    def send_response(self, location1, location3, response):
        response = "{}\n\n[功能列表：输入'基金'可查看预设基金净值估算\n输入'天气'可查询岳麓区当天天气\n" \
                   "输入'大盘'可查看大盘涨跌信息]".format(response)
        pyautogui.click([location1[0] + 50, location1[1] + 50])
        pyperclip.copy(response)
        pyautogui.hotkey('ctrl', 'v')
        time.sleep(2)
        pyautogui.click(location3)

    def send_emoji(self, location1):
        pyautogui.click(location1)
        time.sleep(0.2)
        location2 = pyautogui.locateCenterOnScreen(self.like, confidence=0.9)
        pyautogui.click(location2)
        time.sleep(0.2)
        location3 = pyautogui.locateCenterOnScreen(self.emoji, confidence=0.9)
        pyautogui.click(location3)
        time.sleep(0.2)

    def send(self, text):
        t = Thread(target=self.sendTh, args=(text,))
        t.start()

    def sendTh(self, text):
        con.acquire()
        try:
            loc = pyautogui.locateCenterOnScreen(self.zhizhan, confidence=0.9)
            if loc:
                pyautogui.click(loc)
                time.sleep(0.5)
                location1 = pyautogui.locateCenterOnScreen(self.pos1, confidence=0.9)
                location3 = pyautogui.locateCenterOnScreen(self.sendimg, confidence=0.9)
                location4 = pyautogui.locateCenterOnScreen(self.standby, confidence=0.9)
                self.send_response(location1, location3, text)
                time.sleep(1)
                pyautogui.click(location4)
                time.sleep(1)
        except Exception as e:
            print(e)
        con.notify()
        con.release()

    def timedTask(self):
        t = Thread(target=self.timedTaskTh)
        t.start()

    def timedTaskTh(self):
        con.acquire()
        try:
            loc = pyautogui.locateCenterOnScreen(self.zhizhan, confidence=0.9)
            if loc:
                pyautogui.click(loc)
                time.sleep(0.5)
                location1 = pyautogui.locateCenterOnScreen(self.pos1, confidence=0.9)
                location3 = pyautogui.locateCenterOnScreen(self.sendimg, confidence=0.9)
                location4 = pyautogui.locateCenterOnScreen(self.standby, confidence=0.9)

                funds = config.getFund()
                response = ''
                for f in funds:
                    try:
                        data = fundAccurate(f['fundcode'])
                        response += '自动提醒\n基金代码：{}，基金名称：{}，净值估算：{}，更新时间：{}\n'.format(f['fundcode'], data['name'],
                                                                                     data['gszzl'], data['gztime'])
                        print(data)
                    except Exception as e:
                        print(e)
                        response += '{}\n'.format(str(e))
                self.send_response(location1, location3, response)
                time.sleep(2)
                pyautogui.click(location4)
                time.sleep(1)
        except Exception as e:
            print(e)
        con.notify()
        con.release()

    def run(self):
        self.t = Thread(target=self.monitorTh)
        self.t.start()

    def monitorTh(self):
        try:
            location1, location3, location4 = self.wechat_init()
            pyautogui.click(location4)
            time.sleep(0.1)

            cred = credential.Credential("AKIDrXyB7rQj1EG8mBqhKetugDWacS4RYecM", "avAKHyPcZHkz0mKdhW6Ti6LK3WlkUgbF")
            httpProfile = HttpProfile()
            httpProfile.endpoint = "tbp.tencentcloudapi.com"

            clientProfile = ClientProfile()
            clientProfile.httpProfile = httpProfile
            client = tbp_client.TbpClient(cred, "", clientProfile)

            req = models.TextProcessRequest()

            while True:
                red = self.mainWork()
                con.acquire()
                time.sleep(0.5)
                pyautogui.click(red)
                time.sleep(0.5)
                txt = self.find_txt()
                time.sleep(0.5)
                print(txt)
                if txt == '':
                    self.send_emoji(location1)
                    pyautogui.click(location4)
                    time.sleep(0.5)
                    con.notify()
                    con.release()
                    continue

                if '闭嘴' in txt:
                    self.send_response(location1, location3, '好的，我将闭嘴5分钟！')
                    time.sleep(1)
                    pyautogui.click(location4)
                    con.notify()
                    con.release()
                    time.sleep(5 * 60)
                    continue

                if '基金' == txt:
                    funds = config.getFund()
                    response = ''
                    for f in funds:
                        try:
                            data = fundAccurate(f['fundcode'])
                            response += '基金代码：{}，基金名称：{}，净值估算：{}，更新时间：{}\n'.format(f['fundcode'], data['name'],
                                                                                   data['gszzl'], data['gztime'])
                            print(data)
                        except Exception as e:
                            print(e)
                            response += '{}\n'.format(str(e))
                    self.send_response(location1, location3, response)
                    time.sleep(2)
                    pyautogui.click(location4)
                    time.sleep(1)
                    con.notify()
                    con.release()
                    continue

                if '天气' in txt:
                    self.tianqi()
                    con.notify()
                    con.release()
                    continue

                if '定时' in txt:
                    response = ''
                    for job in weChat.sched.get_jobs():
                        response += '{}\n'.format(str(job))
                    self.send_response(location1, location3, response)
                    time.sleep(2)
                    pyautogui.click(location4)
                    time.sleep(1)
                    con.notify()
                    con.release()
                    continue

                if '大盘' in txt:
                    self.dapan()
                    con.notify()
                    con.release()
                    continue

                funds = config.getFund()
                isFund = False
                for f in funds:
                    if txt in f['name']:
                        try:
                            data = fundAccurate(f['fundcode'])
                            response = '基金代码：{}，基金名称：{}，净值估算：{}，更新时间：{}\n'.format(f['fundcode'], data['name'],
                                                                                  data['gszzl'], data['gztime'])
                            print(data)
                        except Exception as e:
                            print(e)
                            response = '{}\n'.format(str(e))
                        self.send_response(location1, location3, response)
                        time.sleep(2)
                        pyautogui.click(location4)
                        time.sleep(1)
                        con.notify()
                        con.release()
                        isFund = True
                        break

                if isFund:
                    continue

                params = {
                    "BotId": "4db58d18-aa88-4f0f-8402-c2f8b0123926",
                    "BotEnv": "dev",
                    "TerminalId": "0011",
                    "InputText": txt
                }
                req.from_json_string(json.dumps(params))

                resp = client.TextProcess(req)
                try:
                    response = json.loads(resp.to_json_string())['ResponseMessage']['GroupList'][0]['Content']
                except Exception as e:
                    print(e)
                    response = '不明白你在说什么'
                # response = CHAT.txtTotxt(access_token, txt)
                # time.sleep(0.5)
                print(response)
                self.send_response(location1, location3, response)
                time.sleep(1)
                pyautogui.click(location4)
                time.sleep(1)
                con.notify()
                con.release()
        except Exception as e:
            print(e)
            self.monitorTh()

    def dapan(self):
        loc = pyautogui.locateCenterOnScreen(self.zhizhan, confidence=0.9)
        pyautogui.click(loc)
        time.sleep(0.5)
        location1, location3, location4 = self.wechat_init()
        response = ''
        try:
            data = daPanInfos()
            for d in data:
                if d and isinstance(d, list) and len(d) == 11:
                    name = d[1]
                    v1 = d[5]
                    v2 = d[7]
                    v3 = d[8]
                    response += '{} 最新价：{} 涨跌幅：{}\n'.format(name, v1, v3)
        except Exception as e:
            response += str(e)

        self.send_response(location1, location3, response)
        time.sleep(2)
        pyautogui.click(location4)
        time.sleep(1)

    def tianqi(self):
        GetHeaders = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36'
        }
        response = ''
        loc = pyautogui.locateCenterOnScreen(self.zhizhan, confidence=0.9)
        pyautogui.click(loc)
        time.sleep(0.5)
        location1, location3, location4 = self.wechat_init()
        try:
            url = 'https://www.tianqi.com/yueluqu/today/'
            r = get(url=url, headers=GetHeaders, timeout=10)
            r.encoding = 'utf-8'
            if int(r.status_code) != 200:
                response = "Description Failed to crawl data {0}.".format(url)
            if 'error' == r.text or r.text == '':
                response = 'Failed to get web page data correctly {}.'.format(url)

            if response == '':
                data = r.text
                data = etree.HTML(data)
                li_list = data.xpath("//div[@class='zxt_shuju1']/ul/li")
                temps = []
                for li in li_list:
                    t = li.xpath("./span/text()")[0]
                    temps.append(t)

                li_list = data.xpath("//div[@class='day7']/ul[@class='txt txt2']/li")
                weathers = []
                for li in li_list:
                    t = li.xpath("./text()")[0]
                    weathers.append(t)

                li_list = data.xpath("//div[@class='day7']/ul[@class='txt canvas_hour']/li")
                times = []
                for li in li_list:
                    t = li.xpath("./text()")[0]
                    times.append(t)

                response += '今日天气预报\n'
                for i, t in enumerate(times):
                    response += '{}：{}℃ {}\n'.format(t, temps[i], weathers[i])
        except Exception as e:
            response = str(e)

        self.send_response(location1, location3, response)
        time.sleep(2)
        pyautogui.click(location4)
        time.sleep(1)

    def __del__(self):
        self.isExit = True
        if self.t:
            if self.t.is_alive():
                self.t.join(1)

        if not self.sched == None:
            if self.sched.state == STATE_RUNNING:
                self.sched.pause()
            self.sched.remove_all_jobs()


weChat = AutoWechat()

if __name__ == '__main__':
    pass




